package com.ews.onlineexchange.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.assess.Dict;
import com.ews.onlineexchange.model.assess.PeriodType;
import com.ews.onlineexchange.service.assess.AssessRecordService;
import com.ews.onlineexchange.util.PeriodUtils;

@Named
public class UniqueAssessRecordOfPeriodValidator implements Validator {

	@Override
	public void validate( FacesContext context, UIComponent component, Object value ) throws ValidatorException {
	    
	    AssessRecordService service = context.getApplication().evaluateExpressionGet( context, "#{assessRecordService}", AssessRecordService.class );
		
		UIInput supplierInput = (UIInput) context.getViewRoot().findComponent("supplier");
		if ( supplierInput == null ) {
			return;
		}
	    ServiceSupplier supplier = (ServiceSupplier) supplierInput.getSubmittedValue();
	    
	    Dict dict = (Dict) value;
	    
	    if ( dict.getPeriodType().equals( PeriodType.Unique ) || dict.getPeriodType().equals( PeriodType.Repeat ) ) {
	    	return ;
	    }
	    
	    Integer periodYear = PeriodUtils.getPeriodYear( dict.getPeriodType() );
	    Integer periodSn = PeriodUtils.getPeriodSn( dict.getPeriodType() );
	    
	    if ( service.checkExist( supplier, dict, periodYear, periodSn ) ) {
	    	FacesMessage msg = new FacesMessage("相关的事项已经存在,请勿重复提交。");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
		    throw new ValidatorException(msg);
	    }

	}

}
